import os
import matplotlib.pyplot as plt
class SensorDataProcess:
    def __init__(self):
        pass

    def read_data_from_file(self):
        # 获取当前工作目录
        file_path = os.path.join(os.getcwd(), 'MagneticData.txt')
        # 以只读模式打开文件
        column1 = []
        column2 = []
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                for line in file:
                    # 去除行尾的换行符，并按空格分割数据
                    data = line.strip().split()
                    if len(data) == 2:
                        # 将分割后的数据转换为浮点数并添加到相应列的列表中
                        column1.append(float(data[0]))
                        column2.append(float(data[1]))
            return column1, column2
        except FileNotFoundError:
            print("未找到 MagneticData.txt 文件，请检查文件是否存在。")
            return [], []
        
    def GeneratePicture(self):
        num1,num2=self.read_data_from_file()
        number=[i/3 for i in range(len(num1))]

        plt.figure(figsize=(20, 6))
        
        plt.plot(number, num1, color='blue', linewidth=2)  
        plt.plot(number, num2, color='red', linewidth=2)
        
        # 添加标题
        plt.title('Sine and Cosine Curves')
        # 添加 x 轴标签
        plt.xlabel('x')
        # 添加 y 轴标签
        plt.ylabel('y')

        # 显示图例
        plt.legend()

        # 显示网格线
        plt.grid(False)

        # 显示图形
        plt.show()

    def run(self):
        self.GeneratePicture()
        
if __name__ == "__main__":
    data_process = SensorDataProcess()
    data_process.run()
